// packageFT/guide/apply-upgrade/apply-upgrade.js
const app = getApp()
import WxValidate from '../../../utils/WxValidate'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    formData: {
      levelValue: 0,
      levelText: '',
      reason: '',
      pictures: []
    },
    guideLevelColumns: [],
    levelShow: false,
    currentLevel: 0,
    loading: false
  },

  /**
   * 获取导游级别列表
   */
  getGuideLevel: function() {
    const urlStr = app.getNetAddresss('plugin.guide.frontend.level.lists')
    const _this = this
    wx.showLoading({ title: '数据加载中...' })
    app._postNetWork({
      url: urlStr,
      success: function(res) {
        const resData = res.data
        if (resData.result == 1) {
          if (resData.data && resData.data.length) {
            const { currentLevel } = _this.data
            const list = resData.data.map(item => {
              return {
                value: item.id,
                text: item.name,
                disabled: item.id <= currentLevel
              }
            })
            _this.setData({ guideLevelColumns: list })
          }
        } else {
          app.tips(resData.msg || '请求错误！')
        }
      },
      complete: function() {
        wx.hideLoading()
      }
    })
  },

  /**
   * 显示/隐藏弹窗
   * @param {Object} e 
   */
  popupToggle: function(e) {
    const { text, show } = e.currentTarget.dataset
    this.setData({
      [text]: show
    })
  },

  /**
   * 数据双向绑定
   * @param {Object} e 
   */
  updateFormData: function(e) {
    const { formdatakey } = e.currentTarget.dataset
    const value = e.detail
    const key = 'formData.' + [formdatakey]
    this.setData({
      [key]: value 
    })
  },

  /**
   * 申请级别选择确认
   * @param {Object} e 
   */
  levelConfirm: function(e) {
    const { text, value } = e.detail.value
    this.setData({
      'formData.levelText': text,
      'formData.levelValue': value,
      levelShow: false
    })
  },

  /**
   * 图片选中上传(多图)
   * @param {Object} e 
   */
  afterRead: function(e) {
    const { file = [] } = e.detail
    let promiseArray = []
    const uploaderUrl = app.getNetAddresss(app.data.uploaderPicUrl)
    wx.showLoading({
      title: '上传中',
    })
    file.forEach(item => {
      promiseArray.push(new Promise((resolve, reject) => {
        wx.uploadFile({
          filePath: item.url,
          name: 'file',
          url: uploaderUrl,
          success: function(res) {
            resolve(res)
          },
          fail: function(err) {
            reject(err)
          }
        })
      }))
    })
    Promise.all(promiseArray).then(resArray => {
      wx.hideLoading()
      const addUrlArray = resArray.map(item => {
        const resData = JSON.parse(item.data)
        return {url: resData.data.img_url}
      })
      const { formData } = this.data
      const { field } = e.currentTarget.dataset
      const currentImgUrls = [...this.data.formData[field], ...addUrlArray]
      formData[field] = currentImgUrls
      this.setData({ formData })
    }).catch(err => {
      wx.hideLoading()
    })
  },

  /**
   * 删除已上传的图片
   * @param {Object} e 
   */
  deleteFile: function(e) {
    const { index } = e.detail
    const { field } = e.currentTarget.dataset
    let currentData = this.data.formData[field]
    const key = `formData.${field}`
    currentData.splice(index, 1)
    this.setData({
      [key]: currentData
    })
  },

  /**
   * 发布需求
   */
  submitForm: function() {
    if (!this.WxValidate.checkForm(this.data.formData)) {
      const error = this.WxValidate.errorList[0]
      app.tips(error.msg)
      return
    }
    console.log(this.data.formData)
    const { levelValue, pictures, reason } = this.data.formData
    const _this = this
    const images = pictures.map(item => {
      return item.url
    })
    const data = {
      level_id: levelValue,
      text: reason,
      images
    }
    const urlStr = app.getNetAddresss('plugin.guide.frontend.apply.upgrade')
    wx.showLoading({ title: '数据提交中...' })
    this.setData({ loading: true })
    app._postNetWork({
      url: urlStr,
      data,
      success: function(res) {
        const resData = res.data
        if (resData.result == 1) {
          wx.showModal({
            title: '提示',
            content: '申请已提交，等待审核！',
            showCancel: false,
            complete: (resC) => {
              if (resC.confirm) {
                const { tmplIds } = app.data
                wx.requestSubscribeMessage({
                  tmplIds: tmplIds[1],
                  complete: function() {
                    wx.redirectTo({
                      url: '/packageFT/guide/my/my',
                    })
                  }
                })
              }
            }
          })
        } else {
          app.tips(resData.msg || '数据提交失败！')
        }
      },
      complete: function() {
        wx.hideLoading()
        _this.setData({ loading: false })
      }
    })
  },

  /**
   * 表单验证
   */
  initValidate: function() {
    const rules = {
      levelValue: {
        min: 1
      },
      reason: {
        required: true
      }
    }
    const message = {
      levelValue: {
        min: '请选择申请级别'
      },
      reason: {
        required: '请填写申请原因'
      }
    }
    this.WxValidate = new WxValidate(rules, message)
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.setData({ currentLevel: options?.currentLevel ? parseInt(options?.currentLevel) : 0})
    this.getGuideLevel()
    this.initValidate()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})